import { ProColumns, ProTable } from '@/components/Pro';
import { realTimeMonitoringControllerFaultOverview as faultList } from '@/services/ess/realTimeMonitoring';
import { stationAreaControllerImplListStationArea as areaList } from '@/services/ess/stationArea';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import loadsh from 'lodash';
import React, { useEffect, useState } from 'react';
import { useIntl } from 'umi';
import Styles from './index.less';

import {
  useGetDeviceTreeData,
  useParams,
  useSelectedDeviceNode,
  useSetSelectedDevice,
} from '../../SelectedDeviceNodeContext';
interface Props {
  showArea?: boolean;
}
export const FaultOverview: React.FC<Props> = ({ showArea = false }) => {
  const deviceNode = useSelectedDeviceNode();
  const getDeviceTreeData = useGetDeviceTreeData();
  const setSelectedDevice1 = useSetSelectedDevice();
  const [treeData, setTreeData] = useState<API.DeviceInfo[]>([]);
  const [partitions, setPartitions] = useState([]);
  const [barryInfo, setBarryInfo] = useState([]);
  const [tempInfo, setTempInfo] = useState([]);
  const [faultTypes, setFaultTypes] = useState([]);
  const [selectedFaultType, setSelectedFaultType] = useState();
  const params = useParams();
  const intl = useIntl();
  const faultNames = {
    1: barryInfo,
    2: tempInfo,
    3: [],
  };

  const findNode = (name: string) => {
    let nodeReturn = null;
    if (params.treeData.length) {
      for (let node of params.treeData[0]?.children) {
        if (node?.title === name) {
          nodeReturn = node;
          break;
        }
      }
    }
    return nodeReturn;
  };

  //递归操作处理
  const filterNodesRecursively = (nodes, key) => {
    return nodes.filter((node) => {
      if (node.code === key) {
        return true;
      }

      if (node.children) {
        node.children = filterNodesRecursively(node.children, key);
        return node.children.length > 0;
      }

      return false;
    });
  };
  useEffect(() => {
    (async () => {
      try {
        // 并行获取数据
        const [result, barryData, tempData, faultData] = await Promise.all([
          areaList(),
          fetchDictInfo(DATABASE_TYPE_ENUM.BATTERY_FAILURE_TYPE),
          fetchDictInfo(DATABASE_TYPE_ENUM.TEMP_ANOMALY_LAVEL),
          fetchDictInfo(DATABASE_TYPE_ENUM.FAULT_TYPE),
        ]);

        // 处理分区数据
        if (result.success) {
          setPartitions(
            result.data?.map((item) => ({
              value: item?.id,
              label: item?.areaName,
            })) || [],
          );
        }

        // 处理其他字典数据
        setBarryInfo(barryData || []);
        setTempInfo(tempData || []);
        setFaultTypes(faultData || []);

        // 获取树形数据
        let treeDataResult = await getDeviceTreeData();
        let key = deviceNode?.deviceCode;
        if (
          deviceNode?.deviceType === 'AREA' ||
          deviceNode?.nodeType === 'DEVICE_GROUP' ||
          deviceNode?.deviceType === 'STATION'
        ) {
          if (deviceNode?.deviceType === 'STATION') {
            treeDataResult = loadsh.cloneDeep(treeDataResult);
          } else if (deviceNode?.nodeType === 'DEVICE_GROUP') {
            if (params?.hasArea) {
              // let treeData = loadsh.cloneDeep(treeDataResult);
            } else {
              treeDataResult = loadsh.cloneDeep(treeDataResult); //没有分区的情况
            }
          } else {
            treeDataResult = loadsh.cloneDeep(treeDataResult).filter((node) => {
              let name = deviceNode?.deviceName;
              if (node?.name === name) {
                return node;
              }
              return false;
            });
          }
        } else if (
          key !== 'null' &&
          deviceNode?.deviceType !== 'AREA' &&
          deviceNode?.nodeType !== 'DEVICE_GROUP' &&
          key
        ) {
          treeDataResult = loadsh.cloneDeep(treeDataResult).filter((node) => {
            if (node.code === key) {
              return node;
            } else if (node.children) {
              node.children = filterNodesRecursively(node.children, key);
              return node.children.length > 0;
            }
            return false;
          });
        }
        setTreeData(treeDataResult);
      } catch (error) {
        console.error(error);
      }
    })();
  }, [getDeviceTreeData, deviceNode?.deviceType, deviceNode?.key]);

  const columns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }),
      dataIndex: 'pageIndex',
      search: false,
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.zoneName' }),
      dataIndex: 'areaId',
      valueType: 'select',
      fieldProps: {
        options: partitions,
        // mode: 'multiple',
        maxTagCount: 'responsive',
      },
      hideInSearch: !showArea,
      hideInTable: !showArea,
      render: (_, record) => (
        <a
          onClick={() => {
            let node = findNode(record?.areaName);
            setSelectedDevice1(node);
          }}
        >
          {record.areaName}
        </a>
      ),
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.faultType' }),
      dataIndex: 'faultType',
      valueType: 'select',
      fieldProps: {
        options: faultTypes,
        maxTagCount: 'responsive',
        onChange: (value) => {
          setSelectedFaultType(value);
        },
      },
      //后端已经做相应的转换
      // render: (_, record) => {
      //   let arr = faultTypes.filter((res) => Number(res?.value) === Number(record?.faultType));
      //   return arr[0]?.label || '--';
      // },
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.faultName' }),
      dataIndex: 'faultName',
      valueType: 'select',
      fieldProps: {
        options: faultNames[selectedFaultType],
        maxTagCount: 'responsive',
      },
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.faultLocation' }),
      dataIndex: 'faultLocationCodes',
      valueType: 'treeSelect',
      hideInTable: true,
      fieldProps: {
        treeData: treeData,
        fieldNames: {
          label: 'name',
          value: 'code',
          children: 'children',
        },
        multiple: true,
        maxTagCount: 'responsive',
        showSearch: true,
        treeNodeFilterProp: 'name',
        maxCount: 100,
      },
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.faultLocation' }),
      dataIndex: 'faultLocation',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.faultDescription' }),
      dataIndex: 'faultDes',
      search: false,
    },
  ];
  const scroll = {
    x: 'max-content',
    y: 460,
  };

  return (
    <ProTable
      scroll={scroll}
      sticky
      className={Styles.hideXscroll}
      rowKey="pageIndex"
      columns={columns}
      params={{
        deviceCode: deviceNode?.deviceCode ?? undefined,
      }}
      request={async (values) => {
        try {
          let params = {
            deviceType: deviceNode?.deviceType ?? undefined,
            areaId: deviceNode?.areaId?.toString() ?? undefined,
            ...values,
          };

          let reslut = await faultList(params);
          return reslut;
        } catch (err) {
          console.log(err, '错误');
        }
      }}
      search={{}}
    />
  );
};
